import {ListView} from 'antd-mobile';
import React from 'react';
import './less/indexs.less';
import {List, Checkbox, Flex} from 'antd-mobile';
import {Stepper} from 'antd-mobile';
import { Router,Route,hashHistory} from 'react-router';

const data = [
    {
        id: 1,
        icon: 'http://192.168.0.131:8091/ecommerce/20171122100346.png',
        name: '360路由器 极速路由器(购买送礼品,买5包邮)360路由器 极速路由器(购买送礼品,买5包邮)',
        price: 600.00,
        sellerNum: 18,
        distributorNum: 6,
        value: 1,
        checked: false,
    },
    {
        id: 2,
        icon: 'https://zos.alipayobjects.com/rmsportal/XmwCzSeJiqpkuMB.png',
        name: '所有的兼职汪都需要风吹日晒',
        price: 700.00,
        sellerNum: 18,
        distributorNum: 6,
        value: 1,
        checked: false,
    },
    {
        id: 3,
        icon: 'https://zos.alipayobjects.com/rmsportal/hfVtzEhPzTUewPm.png',
        name: '不是所有的兼职汪都需要风吹日晒',
        price: 800.00,
        sellerNum: 18,
        distributorNum: 6,
        value: 1,
        checked: false,
    },
];

const NUM_SECTIONS = 3;
const NUM_ROWS_PER_SECTION = 1;
let pageIndex = 0;
let totalPrice = 0;
let num = 0;

const dataBlobs = {};
let sectionIDs = [];
let rowIDs = [];


function genData(pIndex = 0) {
    for (let i = 0; i < NUM_SECTIONS; i++) {
        const ii = (pIndex * NUM_SECTIONS) + i;
        const sectionName = `Section ${ii}`;
        sectionIDs.push(sectionName);
        dataBlobs[sectionName] = sectionName;
        rowIDs[ii] = [];

        for (let jj = 0; jj < NUM_ROWS_PER_SECTION; jj++) {
            const rowName = `S${ii}, R${jj}`;
            rowIDs[ii].push(rowName);
            dataBlobs[rowName] = rowName;
        }
    }
    sectionIDs = [...sectionIDs];
    rowIDs = [...rowIDs];
}

class Cart extends React.Component {
    constructor(props) {
        super(props);
        const getSectionData = (dataBlob, sectionID) => dataBlob[sectionID];
        const getRowData = (dataBlob, sectionID, rowID) => dataBlob[rowID];

        const dataSource = new ListView.DataSource({
            getRowData,
            getSectionHeaderData: getSectionData,
            rowHasChanged: (row1, row2) => row1 !== row2,
            sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
        });

        this.state = {
            dataSource,
            isLoading: true,
            height: document.documentElement.clientHeight * 3 / 4,
            totalPrice: 0,
            num: 0,
            goodstate: {},
            selectedStores: [],
            checkAll:false,
            goodsNum:0
        };
    }

    chooserAddr = () => {
        hashHistory.push({
            pathname: '/car/orderFills',
            state:
                {
                    data:data,
                    totalPrices:this.state.totalPrice,
                    nums:this.state.num,
                    goodsNum:this.state.goodsNum,
                    goodstate:this.state.goodstate,
                }
        })
    };

    componentWillMount() {
        var goodsStates = this.state.goodstate;
        for (var i = 0; i < data.length; i++) {
            goodsStates["good" + data[i].id] = {value: data[i]["value"], checked: data[i]["checked"]};
        }
        this.setState({
            goodstate: goodsStates,
        });
    }

    componentWillReceiveProps(nextProps) {
        var goodsStates = this.state.goodstate;
        for (var i = 0; i < data.length; i++) {
            goodsStates["good" + data[i].id] = {value: data[i]["value"], checked: data[i]["checked"]};
        }
        this.setState({
            goodstate: goodsStates,
        });
    }

    settperValue = (obj, sectionID, val) => {
        var goodsStates = this.state.goodstate;
        let c = goodsStates["good" + sectionID.id]["value"];
        goodsStates["good" + sectionID.id]["value"] = val;
        this.setState({
            goodstate: goodsStates
        });
        if (this.state.goodstate["good" + sectionID.id]["checked"] == true) {
            this.totalPrice();
        }
    }


    getValue = (obj, sectionID, e) => {
        var checkAll=this.state.checkAll;
        var goodsStates = this.state.goodstate;
        goodsStates["good" + sectionID.id]["checked"] = e.target.checked;
        this.setState({
            goodstate: goodsStates
        });
        if (e.target.checked == true) {
            this.totalPrice();
        }
        else if (e.target.checked == false) {
            checkAll=false;
            this.setState({
                checkAll:checkAll,
            })
        }
        goodsStates["good" + sectionID.id]["checked"] = e.target.checked;
        this.setState({
            goodstate: goodsStates
        });
        this.totalPrice();
        console.log(this.state.goodstate["good" + sectionID.id]["value"]);
        console.log(this.state.goodstate["good" + sectionID.id]["checked"]);
    }

    totalPrice=()=>{
        var totalPrice=this.state.totalPrice;
        var num =this.state.num;
        let goodsNum=0;
        totalPrice=0;
        num=0;
        var goodsStates=this.state.goodstate;
        for (var i = 0; i < data.length; i++){
            if(this.state.goodstate["good" + data[i].id]["checked"] == true){
                goodsNum=goodsNum+1;
                totalPrice=totalPrice+goodsStates["good" + data[i].id]["value"]*data[i].price;
                num=num+goodsStates["good" + data[i].id]["value"];
            }
        }
        this.setState({
            goodsNum:goodsNum,
            totalPrice:totalPrice,
            num:num,
        })
    }

    checkAll = (e) => {
        var checkAll=this.state.checkAll;
        var goodsStates = this.state.goodstate;
        var totalPrice=this.state.totalPrice;
        var num =this.state.num;
        if (e.target.checked == true) {
            checkAll=true;
            for (var key in goodsStates) {
                goodsStates[key]["checked"] = e.target.checked;
            }
            this.setState({
                checkAll:checkAll,
                num:num,
                totalPrice:totalPrice,
                goodstate: goodsStates
            });
            this.totalPrice();
        }else {
            checkAll=false;
            for (var key in goodsStates) {
                goodsStates[key]["checked"] = e.target.checked;
            }
            this.setState({
                checkAll:checkAll,
                totalPrice:totalPrice,
                num:num,
                goodstate: goodsStates
            });
            this.totalPrice();
        }
    }


    componentDidMount() {
        const hei = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop;
        // simulate initial Ajax
        setTimeout(() => {
            genData();
            this.setState({
                dataSource: this.state.dataSource.cloneWithRowsAndSections(dataBlobs, sectionIDs, rowIDs),
                isLoading: false,
                height: hei,
            });
        }, 600);
    }

    render() {
        const separator = (sectionID, rowID) => (
            <div
                key={`${sectionID}-${rowID}`}
                style={{
                    backgroundColor: '#F5F5F9',
                    height: 8,
                    borderTop: '1px solid #ECECED',
                    borderBottom: '1px solid #ECECED',
                }}
            />
        );
        let index = data.length - 1;
        const row = (rowData, sectionID, rowID) => {
            if (index < 0) {
                index = data.length - 1;
            }
            const obj = data[index--];
            return (
                <div key={rowID} style={{padding: '0 15px'}}>
                    <div className="line"></div>
                    <div className="checkBox">
                        <Checkbox
                            checked={this.state.goodstate['good' + obj.id]['checked']}
                            onChange={this.getValue.bind(this, sectionID, obj)}
                        >
                        </Checkbox></div>
                    <div className="cell">
                        <img src={obj.icon} alt=""/>
                        <div className="cellContent">
                            <div className="lineLimit cellDesc cellCommom">{obj.name}</div>
                            <div style={{marginTop: '40px'}} className="cellCommom">
                                <div className="textPosition">
                                    <span style={{fontSize: '28px', color: '#FF6E27'}}>¥ {obj.price}</span></div>
                                <div className="textPosition">
                                    <Stepper
                                        className='stepper'
                                        style={{width: '80%', minWidth: '100px', marginLeft: '140px'}}
                                        showNumber={true}
                                        max={999}
                                        min={1}
                                        defaultValue={1}
                                        onChange={this.settperValue.bind(this, sectionID, obj)}
                                    />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            );
        };
        return (
            <div>
                <div>
                    <ListView
                        ref={el => this.lv = el}
                        dataSource={this.state.dataSource}
                        renderRow={row}
                        renderSeparator={separator}
                        style={{
                            height: this.state.height,
                            overflow: 'auto',
                            zIndex: '9'
                        }}
                        pageSize={4}
                        scrollRenderAheadDistance={500}
                    />
                </div>
                <div className='paySelect'>
                    <div style={{float: 'left', marginLeft: '15px'}}>
                        <Checkbox
                            onChange={this.checkAll}
                            checked={this.state.checkAll}
                        >全选</Checkbox></div>
                    <div onClick={this.chooserAddr} style={{
                        marginLeft: '10px',
                        backgroundColor: '#ff6215',
                        float: 'right',
                        height: '1.2rem',
                        width: '30%',
                        lineHeight: '1.2rem',
                        color:' #FFFFFF',
                        textAlign:'center',
                    }}>&nbsp;结算（{this.state.num}）
                    </div>
                    <div style={{float: 'right'}}>
                        <span>合计：</span><span
                        style={{fontSize: '32px', color: '#FF6E27'}}>￥{this.state.totalPrice}</span>
                        <span style={{fontSize: '28px', color: '#CDC1C5', marginLeft: '5px'}}>(不含邮费)</span>
                    </div>

                </div>
            </div>
        );
    }
}
export default Cart;